package cn.edu.niit.studyspace.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import org.litepal.crud.DataSupport;

import java.lang.ref.WeakReference;
import java.util.List;

import cn.edu.niit.studyspace.R;
import cn.edu.niit.studyspace.activity.CourseModifyActivity;
import cn.edu.niit.studyspace.bean.Course;

public class CourseAdapter extends RecyclerView.Adapter <CourseAdapter.ViewHolder>{
    private WeakReference<Context> wr;
    private List<Course> courses;

    public CourseAdapter(Context context, List<Course> courses) {
        wr = new WeakReference<>(context);
        this.courses = courses;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(wr.get()).inflate(R.layout.item_course,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
       Course course=courses.get(position);

        viewHolder.iv_delete.setOnClickListener(view -> {
            //TODO----点击删除------
            DataSupport.delete(Course.class, course.getId());
            courses = DataSupport.findAll(Course.class, true);
            notifyData(courses);
        });
       viewHolder.name.setOnClickListener(view -> {
            //todo---点击修改----
            Intent intent = new Intent(wr.get(), CourseModifyActivity.class);
            intent.putExtra("cId", course.getId());
            wr.get().startActivity(intent);
        });
        viewHolder.name.setText(course.getName());
        viewHolder.teacher.setText(course.getTeacher());
    }

    @Override
    public int getItemCount() {
        return courses.size();
    }

    public void notifyData(List<Course> courses) {
        this.courses = courses;
        notifyDataSetChanged();
    }


    static class ViewHolder extends RecyclerView.ViewHolder{
        TextView name;
        TextView teacher;
     ImageView iv_delete;



        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            teacher = itemView.findViewById(R.id.tv_item_course_teacher);
            name = itemView.findViewById(R.id.tv_item_course_name);
            iv_delete = itemView.findViewById(R.id.iv_delete_course);
        }
    }
}
